/**
 * 辅助工具
 */
var GrdAssist = {
    /**
     * 计算
     * @param {any} expression
     * @param {any} precision
     * @param {any} isThrowError
     */
    calculateByExpression: function (expression, precision, isThrowError) {
        try {
            return parseFloat(eval(expression).toFixed(precision, !precision || precision === null || precision === undefined || precision === "" ? 0 : precision));
        } catch (e) {
            if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
                throw this.createErrorObject("对{0}进行解析计算出错，错误原因是：{1}", [expression, e.message]);
            }
        }
    },
    /**
     * 比较两个时间大小
     */
    timeCompare: function (startTimeString, endTimeString, isThrowError) {
        try {
            return Date.parse(startTimeString) >= Date.parse(endTimeString);
        } catch (e) {
            if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
                throw this.createErrorObject("比较两个时间的大小时出错，错误原因是：{0}", [e.message]);
            }
        }
    },

    /**
     * 计算天数差的函数，通用
     */
    dateDiff: function (startTimeString, endTimeString, isThrowError) {
        try {
            var aDate, oDate1, oDate2, iDays;
            aDate = sDate1.split("-");
            oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);  //转换为12-18-2002格式
            aDate = sDate2.split("-");
            oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
            iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24);  //把相差的毫秒数转换为天数
            return iDays;
        } catch (e) {
            if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
                throw this.createErrorObject("计算两个时间的差出错，错误原因是：{0}", [e.message]);
            }
        }
    },

    /**
     * 
     */
    createStringSplitByCommaFromArray: function (rows, fieldName) {
        try {
            var retString = "";
            $.each(rows, function (index, item) {
                retString += "'" + item[fieldName] + "',";
            });
            retString = retString.replace(/,$/gi, "");
            return retString;
        } catch (e) {
            throw e;
        }
    },

    /**
     * 解码
     */
    tryDecodeURIComponent: function (value, isThrowError) {
        try {
            return decodeURIComponent(value);
        } catch (e) {
            if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
                throw this.createErrorObject("对{0}解码时出现错误，错误原因是：{1}", [value, e.message]);
            }
        }
    },

    /**
     * js中获取地址参数
     */
    queryString: function (value, isThrowError) {
        try {
            var sValue = location.search.match(new RegExp("[\?\&]" + value + "=([^\&]*)(\&?)", "i"));
            return sValue ? sValue[1] : sValue
        } catch (e) {
            if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
                throw this.createErrorObject("js中获取地址参数，错误原因是：{1}", [value, e.message]);
            }
        }
    },

    /**
     * 删除url中指定的参数
     */
    urlParamDe: function (url, name) {
        var sValue = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]*)(\&?)", "i"))
        if (sValue == null) { return url; }
        var reg = sValue[0];
        if (reg.substr(reg.length - 1, reg.length) == "&") {
            reg = reg.substr(0, reg.length - 1);
        }
        return url.replace(reg, "");
    },

    /**
     * createErrorObject
     * @param {any} formatString
     * @param {any} error
     */
    createErrorObject: function (formatString, error) {
        return new Error(formatString.format(error));
    },

    /**
     * 对象转换
     */
    fromJson: function (json, isThrowError) {
        try {
            return this.isString(json) ? JSON.parse(json) : json;
        } catch (e) {
            if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
                throw this.createErrorObject("对{0}转换对象时出错，错误原因是：{1}", [json, e.message]);
            }
        }
    },

    /**
     * 时间格式化
     */
    formatJsonDate: function (jsondate, format) {
        jsondate = jsondate + "";
        if (!/^\/Date[(].+[)]\/$/.test(jsondate))
            return jsondate.replace("T", " ");
        jsondate = jsondate.replace("/Date(", "").replace(")/", "");
        if (jsondate.indexOf("+") > 0) {
            jsondate = jsondate.substring(0, jsondate.indexOf("+"));
        }
        else if (jsondate.indexOf("-") > 0) {
            jsondate = jsondate.substring(0, jsondate.indexOf("-"));
        }
        var datetime = new Date(parseInt(jsondate, 10));
        if (!format) format = "yyyy-MM-dd";
        return datetime.Format(format);
    },

    /**
     *  date为 英文开头格式
     *  formatDate(date,"yyyy-MM-dd HH:mm")
     */
    formatDate: function (now, mask) {
        if (toString.call(now) !== '[object Date]') {
            now = new Date(now);
        }
        var d = now;
        var zeroize = function (value, length) {
            if (!length) length = 2;
            value = String(value);
            for (var i = 0, zeros = ''; i < (length - value.length); i++) {
                zeros += '0';
            }
            return zeros + value;
        };

        return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0) {
            switch ($0) {
                case 'd': return d.getDate();
                case 'dd': return zeroize(d.getDate());
                case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
                case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
                case 'M': return d.getMonth() + 1;
                case 'MM': return zeroize(d.getMonth() + 1);
                case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
                case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
                case 'yy': return String(d.getFullYear()).substr(2);
                case 'yyyy': return d.getFullYear();
                case 'h': return d.getHours() % 12 || 12;
                case 'hh': return zeroize(d.getHours() % 12 || 12);
                case 'H': return d.getHours();
                case 'HH': return zeroize(d.getHours());
                case 'm': return d.getMinutes();
                case 'mm': return zeroize(d.getMinutes());
                case 's': return d.getSeconds();
                case 'ss': return zeroize(d.getSeconds());
                case 'l': return zeroize(d.getMilliseconds(), 3);
                case 'L': var m = d.getMilliseconds();
                    if (m > 99) m = Math.round(m / 10);
                    return zeroize(m);
                case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
                case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
                case 'Z': return d.toUTCString().match(/[A-Z]+$/);
                // Return quoted strings with the surrounding quotes removed
                default: return $0.substr(1, $0.length - 2);
            }
        });
    },

    /**
     * 随机数
     * @param {any} under
     * @param {any} over
     */
    randomBy: function (under, over) {
        switch (arguments.length) {
            case 1: return parseInt(Math.random() * under + 1);
            case 2: return parseInt(Math.random() * (over - under + 1) + under);
            default: return 0;
        }
    },

    /** 
     * 将数值四舍五入(保留2位小数)后格式化成金额形式 
     * @param number 数值(Number或者String) 
     * @return 金额格式的字符串,如'1,234,567.45' 
     * @type String 
     */
    formatMoney: function (number) {
        number = number.toString().replace(/\$|\,/g, '');
        if (isNaN(number))
            number = "0";
        var sign = (number == (number = Math.abs(number)));
        number = Math.floor(number * 100 + 0.50000000001);
        var cents = number % 100;
        number = Math.floor(number / 100).toString();
        if (cents < 10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((number.length - (1 + i)) / 3); i++)
            number = number.substring(0, number.length - (4 * i + 3)) + ',' +
                number.substring(number.length - (4 * i + 3));
        return (((sign) ? '' : '-') + number + '.' + cents);
    },

    /*
    *获取select下拉菜单所有信息
    */
    getSelectAllTest: function (selectName) {
        var ret = new Array();
        $("#" + selectName + " option").each(function () {
            //遍历所有option  
            var value = $(this).val();   //获取option值   
            var text = $(this).text();
            if (text != '') {
                var o = new Element(value, text, 0);
                ret.push(o);
            }
        });
        return ret;
    },

    /*
    *获取select下拉菜单所有信息的值
    */
    getSelectAllValue: function (selectName) {
        var ret = new Array();
        $("#" + selectName + " option").each(function () {
            //遍历所有option  
            var value = $(this).val();  //获取option值   
            ret.push(value);
        });
        return ret;
    },

    /**获取月份对应的天数 */
    getMonthDates: function (year, month) {
        var date = new Date(year, month, 0);
        var days = date.getDate();
        return days;
    },

    /**
     * 获取两个时间段内的所有日期列表
     * @param {any} start
     * @param {any} end
     */
    getDiffDate: function (start, end) {
        var startTime = getDate(start);
        var endTime = getDate(end);
        var dateArr = [];
        while ((endTime.getTime() - startTime.getTime()) > 0) {
            var year = startTime.getFullYear();
            var month = startTime.getMonth().toString().length === 1 ? "0" + (parseInt(startTime.getMonth().toString(), 10) + 1) : (startTime.getMonth() + 1);
            var day = startTime.getDate().toString().length === 1 ? "0" + startTime.getDate() : startTime.getDate();
            dateArr.push(year + "-" + month + "-" + day);
            startTime.setDate(startTime.getDate() + 1);
        }
        return dateArr;
    },
    /**
     * 获取两个日期中所有的月份
     * @param {any} start
     * @param {any} end
     */
    getDiffMoth: function (start, end) {
        var result = [];
        var s = start.split("-");
        var e = end.split("-");
        var min = new Date();
        var max = new Date();
        min.setFullYear(s[0], s[1]);
        max.setFullYear(e[0], e[1]);
        var curr = min;
        while (curr <= max) {
            var month = curr.getMonth();

            //var str = curr.getFullYear() + "-" + (month);
            //var s = curr.getFullYear() + "-0";
            //if (str == s) {
            //    str = curr.getFullYear() + "-12";
            //}
            //result.push(str);
            result.push(curr.getFullYear() + "-" + (month < 10 ? ("0" + month) : month));  
            curr.setMonth(month + 1);
        }
        return result;  
    }
}



